// 用户认证和权限管理
export function initAuthSystem() {
  // 用户状态
  let currentUser = null;
  let isAdmin = false;

  // 从localStorage获取用户信息
  function loadUserFromStorage() {
    try {
      const userData = localStorage.getItem('voice_community_user');
      if (userData) {
        const user = JSON.parse(userData);
        currentUser = user;
        isAdmin = user.role === 'admin';
        updateUI();
        return true;
      }
    } catch (error) {
      console.error('加载用户信息失败:', error);
      localStorage.removeItem('voice_community_user');
    }
    return false;
  }

  // 保存用户信息到localStorage
  function saveUserToStorage(user, token) {
    try {
      const userData = {
        ...user,
        token: token
      };
      localStorage.setItem('voice_community_user', JSON.stringify(userData));
      return true;
    } catch (error) {
      console.error('保存用户信息失败:', error);
      return false;
    }
  }

  // 清除用户信息
  function clearUserFromStorage() {
    localStorage.removeItem('voice_community_user');
    currentUser = null;
    isAdmin = false;
  }

  // 更新UI显示
  function updateUI() {
    const loginSection = document.getElementById('login-section');
    const userInfo = document.getElementById('user-info');
    const adminControls = document.querySelectorAll('.admin-only');
    const guestControls = document.querySelectorAll('.guest-only');

    if (isAdmin) {
      // 管理员界面
      if (loginSection) loginSection.style.display = 'none';
      if (userInfo) {
        userInfo.style.display = 'block';
        userInfo.innerHTML = `
          <div class="flex items-center space-x-4">
            <span class="text-sm text-gray-600">管理员: ${currentUser.username}</span>
            <button id="logout-btn" class="text-sm text-red-600 hover:text-red-800">退出登录</button>
          </div>
        `;
      }
      
      // 显示管理员功能
      adminControls.forEach(control => {
        control.style.display = 'block';
        control.classList.remove('hidden');
      });
      
      // 隐藏游客功能
      guestControls.forEach(control => {
        control.style.display = 'none';
        control.classList.add('hidden');
      });
    } else {
      // 游客界面
      if (loginSection) loginSection.style.display = 'block';
      if (userInfo) userInfo.style.display = 'none';
      
      // 隐藏管理员功能
      adminControls.forEach(control => {
        control.style.display = 'none';
        control.classList.add('hidden');
      });
      
      // 显示游客功能
      guestControls.forEach(control => {
        control.style.display = 'block';
        control.classList.remove('hidden');
      });
    }
  }

  // 显示登录模态框
  function showLoginModal() {
    const modal = document.getElementById('login-modal');
    if (modal) {
      modal.style.display = 'flex';
      document.getElementById('login-username').focus();
    }
  }

  // 隐藏登录模态框
  function hideLoginModal() {
    const modal = document.getElementById('login-modal');
    if (modal) {
      modal.style.display = 'none';
      // 清空表单
      document.getElementById('login-form').reset();
    }
  }

  // 处理登录
  async function handleLogin(event) {
    event.preventDefault();
    
    const username = document.getElementById('login-username').value.trim();
    const password = document.getElementById('login-password').value.trim();
    
    if (!username || !password) {
      showMessage('请输入用户名和密码', 'error');
      return;
    }

    try {
      showMessage('正在登录...', 'info');
      
      const response = await fetch('/api/auth/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, password })
      });

      const result = await response.json();

      if (result.success) {
        currentUser = result.user;
        isAdmin = result.user.role === 'admin';
        
        if (saveUserToStorage(currentUser, result.token)) {
          updateUI();
          hideLoginModal();
          showMessage(`欢迎回来，${currentUser.username}！`, 'success');
        } else {
          showMessage('登录成功，但保存用户信息失败', 'warning');
        }
      } else {
        showMessage(result.message || '登录失败', 'error');
      }
    } catch (error) {
      console.error('登录失败:', error);
      showMessage('登录失败，请检查网络连接', 'error');
    }
  }

  // 处理退出登录
  function handleLogout() {
    if (confirm('确定要退出登录吗？')) {
      clearUserFromStorage();
      updateUI();
      showMessage('已退出登录', 'info');
    }
  }

  // 显示消息
  function showMessage(message, type) {
    const messageDiv = document.getElementById('auth-message');
    if (messageDiv) {
      messageDiv.className = 'text-sm p-2 rounded';
      messageDiv.classList.remove('hidden');
      
      if (type === 'success') {
        messageDiv.className += ' bg-green-100 text-green-800 border border-green-200';
      } else if (type === 'error') {
        messageDiv.className += ' bg-red-100 text-red-800 border border-red-200';
      } else if (type === 'warning') {
        messageDiv.className += ' bg-yellow-100 text-yellow-800 border border-yellow-200';
      } else {
        messageDiv.className += ' bg-blue-100 text-blue-800 border border-blue-200';
      }
      
      messageDiv.textContent = message;
      
      // 3秒后自动隐藏
      setTimeout(() => {
        messageDiv.classList.add('hidden');
      }, 3000);
    }
  }

  // 检查权限
  function checkPermission(action) {
    switch (action) {
      case 'upload':
      case 'delete':
        return isAdmin;
      case 'view':
      case 'play':
        return true; // 所有用户都可以查看和播放
      default:
        return false;
    }
  }

  // 初始化事件监听器
  function initEventListeners() {
    // 登录按钮
    const loginBtn = document.getElementById('login-btn');
    if (loginBtn) {
      loginBtn.addEventListener('click', showLoginModal);
    }

    // 登录表单
    const loginForm = document.getElementById('login-form');
    if (loginForm) {
      loginForm.addEventListener('submit', handleLogin);
    }

    // 退出登录按钮
    document.addEventListener('click', (e) => {
      if (e.target.id === 'logout-btn') {
        handleLogout();
      }
    });

    // 关闭模态框
    const modal = document.getElementById('login-modal');
    if (modal) {
      modal.addEventListener('click', (e) => {
        if (e.target === modal) {
          hideLoginModal();
        }
      });
    }

    // ESC键关闭模态框
    document.addEventListener('keydown', (e) => {
      if (e.key === 'Escape') {
        hideLoginModal();
      }
    });
  }

  // 初始化
  function init() {
    initEventListeners();
    loadUserFromStorage();
    updateUI();
  }

  // 公共API
  return {
    init,
    isAdmin: () => isAdmin,
    currentUser: () => currentUser,
    checkPermission,
    showLoginModal,
    logout: handleLogout
  };
}
